
package com.android.finaltracer.ui;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.android.finaltracer.R;
import com.android.finaltracer.engine.EngineService;
import com.android.finaltracer.model.FTDataProvider.RelationColumns;
import com.android.finaltracer.model.FTProviderInterface;
import com.android.finaltracer.model.SettingCreator;
import com.android.finaltracer.model.UserBindInfo;

public class BindCnfActivity extends Activity {
    public static final String USERBINDINFO_COMMAND = "command";
    public static final String FROM_WHO = "from";
    public static final String USERBINDINFO_PHONENUM = "phonenum";
    public static final String USERBINDINFO_IMEI = "imei";
    public static final String USERBINDINFO_ACCEPT = "accept";
    public static final String USERBINDINFO_REQ_BIND = "bindreq";
    private TextView tip_tv, bind_tip_tv;
    private CheckBox bind_cb;
    private int command;
    private String from, phoneNum, imei;
    private Button ok_btn, cancel_btn;
    private boolean isAccept, isReqBind;
    Messenger mService = null;
    private boolean mBound = false;

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        // super.onNewIntent(intent);
        setIntent(intent);
    }

    private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub
            mService = null;
            mBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bind_cnf);
        initIntent();
        findViews();
        initData();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        bindService();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        // unBindService();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unBindService();
    }

    private void initIntent() {
        Intent intent = getIntent();
        command = intent.getIntExtra(USERBINDINFO_COMMAND,
                UserBindInfo.USERBINDINFO_NO_COMMAND);
        from = intent.getStringExtra(FROM_WHO);
        phoneNum = intent.getStringExtra(USERBINDINFO_PHONENUM);
        imei = intent.getStringExtra(USERBINDINFO_IMEI);
        isAccept = intent.getBooleanExtra(USERBINDINFO_ACCEPT, false);
        isReqBind = intent.getBooleanExtra(USERBINDINFO_REQ_BIND, false);
    }

    private void findViews() {
        tip_tv = (TextView) findViewById(R.id.tip_tv);
        bind_cb = (CheckBox) findViewById(R.id.bind_cb);
        bind_tip_tv = (TextView) findViewById(R.id.bind_tip_tv);
        ok_btn = (Button) findViewById(R.id.ok_btn);
        cancel_btn = (Button) findViewById(R.id.cancel_btn);
        switch (command) {
            // time out only from info can be known, others are null
            case UserBindInfo.USERBINDINFO_NO_COMMAND:
                tip_tv.setText(String.format(
                        getResources().getString(R.string.remote_bind_time_out),
                        from));
                ok_btn.setText(getResources().getString(R.string.remot_bind_cnf));
                break;
            case UserBindInfo.REMOTE_BIND_PHONE_REQ:
                tip_tv.setText(String.format(
                        getResources().getString(R.string.remote_bind_req), from));
                bind_cb.setVisibility(View.VISIBLE);
                bind_tip_tv.setVisibility(View.VISIBLE);
                cancel_btn.setVisibility(View.VISIBLE);
                break;
            case UserBindInfo.REMOTE_BIND_PHONE_CNF:
                if (isAccept && isReqBind) {
                    tip_tv.setText(String.format(
                            getResources().getString(
                                    R.string.remote_bind_cnf_and_bind_req), from));
                    // bind_cb.setVisibility(View.VISIBLE);
                    // bind_tip_tv.setVisibility(View.VISIBLE);
                    cancel_btn.setVisibility(View.VISIBLE);
                } else if (isAccept) {
                    tip_tv.setText(String.format(
                            getResources().getString(
                                    R.string.remote_accept_bind_req), from));
                    ok_btn.setText(getResources()
                            .getString(R.string.remot_bind_cnf));
                } else {
                    tip_tv.setText(String.format(
                            getResources().getString(
                                    R.string.remote_reject_bind_req), from));
                    ok_btn.setText(getResources()
                            .getString(R.string.remot_bind_cnf));
                }
                break;
            case UserBindInfo.REMOTE_BIND_PHONE_RSP:
                if (isAccept) {
                    tip_tv.setText(String.format(
                            getResources().getString(
                                    R.string.remote_accept_bind_req), from));
                    ok_btn.setText(getResources()
                            .getString(R.string.remot_bind_cnf));
                } else {
                    tip_tv.setText(String.format(
                            getResources().getString(
                                    R.string.remote_reject_bind_req), from));
                    ok_btn.setText(getResources()
                            .getString(R.string.remot_bind_cnf));
                }
                break;
            default:
                break;
        }
    }

    private int msgWhat;
    private UserBindInfo acceptUserBindInfo, rejectUserBindInfo;
    private ContentValues values;

    private void initData() {
        msgWhat = EngineService.MSG_NOTHING;
        switch (command) {
            case UserBindInfo.USERBINDINFO_NO_COMMAND:
                break;
            case UserBindInfo.REMOTE_BIND_PHONE_REQ:
                msgWhat = EngineService.MSG_UI_SERVICE_BIND_PHONE_CNF;
                acceptUserBindInfo = new UserBindInfo(
                        UserBindInfo.REMOTE_BIND_PHONE_CNF, from,
                        bind_cb.isChecked() ? SettingCreator.settingInit(
                                BindCnfActivity.this).getImeiStr() : null, true);
                rejectUserBindInfo = new UserBindInfo(
                        UserBindInfo.REMOTE_BIND_PHONE_CNF, from, null);
                values = new ContentValues();
                values.put(RelationColumns.NUMBER, from);
                values.put(RelationColumns.IMEI, imei);
                break;
            case UserBindInfo.REMOTE_BIND_PHONE_CNF:
                msgWhat = EngineService.MSG_UI_SERVICE_BIND_PHONE_RSP;
                if (isAccept && isReqBind) {
                    acceptUserBindInfo = new UserBindInfo(
                            UserBindInfo.REMOTE_BIND_PHONE_RSP, from, null, true);
                    rejectUserBindInfo = new UserBindInfo(
                            UserBindInfo.REMOTE_BIND_PHONE_RSP, from, null);
                    values = new ContentValues();
                    values.put(RelationColumns.NUMBER, from);
                    values.put(RelationColumns.IMEI, imei);
                    values.put(RelationColumns.WEIGHT_TYPE,
                            RelationColumns.WEIGHT_TYPE_BINDED);
                } else if (isAccept) {
                    values = new ContentValues();
                    values.put(RelationColumns.NUMBER, from);
                    values.put(RelationColumns.WEIGHT_TYPE,
                            RelationColumns.WEIGHT_TYPE_BINDED);
                    // acceptUserBindInfo=new
                    // UserBindInfo(UserBindInfo.REMOTE_BIND_PHONE_RSP, from,
                    // null);
                    // rejectUserBindInfo=new
                    // UserBindInfo(UserBindInfo.REMOTE_BIND_PHONE_RSP, from,
                    // null);
                }
                break;
            case UserBindInfo.REMOTE_BIND_PHONE_RSP:
                if (isAccept) {
                    values = new ContentValues();
                    values.put(RelationColumns.NUMBER, from);
                    values.put(RelationColumns.WEIGHT_TYPE,
                            RelationColumns.WEIGHT_TYPE_BINDED);
                }
                break;
            default:
                break;
        }
        // ok_btn.setOnClickListener(new mbtnOnClickListener(msgWhat,
        // acceptUserBindInfo));
        // cancel_btn.setOnClickListener(new mbtnOnClickListener(msgWhat,
        // rejectUserBindInfo));
        ok_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (!mBound) {
                    return;
                }
                try {
                    if (acceptUserBindInfo != null) {
                        if (command == UserBindInfo.REMOTE_BIND_PHONE_REQ) {
                            acceptUserBindInfo.setRequestBind(bind_cb
                                    .isChecked());
                        }
                        mService.send(Message.obtain(null, msgWhat,
                                acceptUserBindInfo));
                    }
                    saveInfo();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                finish();
            }
        });
        cancel_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!mBound) {
                    return;
                }
                try {
                    if (rejectUserBindInfo != null) {
                        mService.send(Message.obtain(null, msgWhat,
                                rejectUserBindInfo));
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                finish();
            }
        });
    }

    private void bindService() {
        if (mBound) {
            return;
        }
        // bind service
        Intent serviceIntent = new Intent(this, EngineService.class);
        bindService(serviceIntent, mConn, Context.BIND_AUTO_CREATE);
    }

    private void unBindService() {
        if (!mBound) {
            return;
        }
        unbindService(mConn);
    }

    private void saveInfo() {
        SettingCreator.settingInit(this).setSelfNumber(phoneNum);
        // to be added
        if (values != null) {
            FTProviderInterface.getInstance(this).saveRelationNumber(values);
        }
    }

    // private class mbtnOnClickListener implements OnClickListener{
    // private int msgwhat;
    // private UserBindInfo userBindInfo;
    // @Override
    // public void onClick(View v) {
    // // TODO Auto-generated method stub
    // if (!mBound) {
    // return;
    // }
    // try {
    // mService.send(Message.obtain(null,this.msgwhat,this.userBindInfo));
    // } catch (RemoteException e) {
    // e.printStackTrace();
    // }
    // finish();
    // }
    // public mbtnOnClickListener(int msgwhat, UserBindInfo userBindInfo) {
    // super();
    // this.msgwhat = msgwhat;
    // this.userBindInfo = userBindInfo;
    // }
    //
    // }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
